﻿using System.Collections.Generic;
using System.Linq;
using Metro.Kashikoi.Common;
using Metro.Kashikoi.Service.Common.Management;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace Metro.Kashikoi.Management
{
    /// <summary>
    /// This class provides methods to manage the services.
    /// </summary>
    public class ServiceManager
    {
        private static readonly ServiceManager instance = new ServiceManager();

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceManager"/> class.
        /// </summary>
        private ServiceManager()
        {
            Services = new Dictionary<string, IServiceManager>();
        } 

        #endregion

        #region Properties

        /// <summary>
        /// Gets the instance.
        /// </summary>
        public static ServiceManager Instance { get { return instance; } }

        /// <summary>
        /// Gets or sets the services.
        /// </summary>
        /// <value>
        /// The services.
        /// </value>
        private IDictionary<string, IServiceManager> Services { get; set; }

        /// <summary>
        /// Gets the service.
        /// </summary>
        public ICollection<string> ServiceName { get { return Services.Keys.ToList(); } } 

        #endregion

        #region Public Methods

        /// <summary>
        /// Initializes this service.
        /// </summary>
        public void Initialize()
        {
            IUnityContainer container = new UnityContainer()
                .LoadConfiguration(Constants.UnityContainerServiceManager);
            string typeName = typeof(IServiceManager).Name;
            foreach (var item in container.Registrations)
            {
                if (item.RegisteredType.Name.Equals(typeName))
                {
                    Services.Add(item.Name, container.Resolve<IServiceManager>(item.Name));
                }
            }
        }

        /// <summary>
        /// Starts this service.
        /// </summary>
        public void Start()
        {
            foreach (var item in Services.Keys)
            {
                Services[item].Initialize();
                Services[item].Start();
            }
        }

        /// <summary>
        /// Stops this service.
        /// </summary>
        public void Stop()
        {
            foreach (var item in Services.Keys)
            {
                Services[item].Stop();
            }
        } 

        #endregion
    }
}
